<template>
    <div class="">
        <van-search v-model="searchWord" placeholder="请输入单词" show-action @update:model-value="asyncSearch"
            @search="asyncSearch" @input="asyncSearch" :show-loading="isLoading">
            <template #action>
                <van-icon name="search" />
            </template>
        </van-search>

        <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="loadMoreWords">
            <van-cell class="vancell" v-for="(item, index) in suggestions" :key="index" :title="item"
                @click="selectSuggestion(item)">

            </van-cell>
        </van-list>



        <van-form ref="formRef" :model="form">
            <van-field name="name" placeholder="输入单词名称" v-model="form.name" label="含义" :rules="[{ required: true, message: '请填写单词' }]" />
            <van-field name="definition" placeholder="输入单词含义" v-model="form.definition" label="释义"
                :rules="[{ required: true, message: '请填写单词中文含义' }]" />
            <van-field name="remark" placeholder="输入单词备注" type="textarea" v-model="form.remark" label="备注信息" />
            <van-cell-group>
                <van-cell title="查看详情" is-link="" @click="showWord = true" />
            </van-cell-group>
            <van-popup v-model:show="showWord" round closeable close-icon="close" style="width: 100%; height: 100%;">
                <iframe :src="'https://mobile.youdao.com/dict?le=eng&q=' + searchWord"
                    style="width: 100%;height: 100%; margin-top: 40px">

                </iframe>
            </van-popup>
            <div style="margin-top: 10px;text-align: center;">
                <van-button type="primary" @click="submitForm">确认添加</van-button>
            </div>

        </van-form>
        <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">这是已经添加的单词</van-divider>


        <van-list v-model:loading="loadingWords" :finished="finishedWords" finished-text="没有更多了" @load="onLoad">
            <van-cell v-for="(item, index) in wordList" :key="index" :title="item.name + ' ' + item.definition">
                <van-button type="danger" size="mini" @click="deleteWord(index,item.id)">删除单词</van-button>
                <van-button type="primary" size="mini"
                    @click="showTargetWord = true; targetWord = item">查看详细信息</van-button>
            </van-cell>
        </van-list>

        <van-popup v-model:show="showTargetWord" round closeable close-icon="close" style="width: 100%;height: 100%;">
            <p style="font-size: bold; color: red;">{{ targetWord.remark }}</p>
            <iframe :src="'https://mobile.youdao.com/dict?le=eng&q=' + targetWord.name"
                style="width: 100%;height: 100%;margin-top: 40px;">

            </iframe>
        </van-popup>

    </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
// import { VanSearch, VanForm, VanField, VanButton, VanIcon, VanDropdownMenu, VanDropdownItem } from 'vant';
import axios from 'axios';
import { url } from '@/interface';
import { useRoute } from 'vue-router';

const routes = useRoute();

// 单词搜索输入框的绑定值
const searchWord = ref('');
// 表单数据
const form = reactive({
    wordBookId: 12,
    name: '',
    definition: '',
    pronunciation: '',
    remark: ''
});
// 表单引用
const formRef = ref(null);
// 是否正在加载（用于显示搜索框的加载动画）
const isLoading = ref(false);
// 搜索建议列表
const suggestions = ref([]);

const showWord = ref(false);


// 下拉时加载更多的候选单词
let page = 1;
const loading = ref(false);
const finished = ref(true);
// const readMoreSuggestions = ref(false);
// 输入框内容变化时触发的方法（异步获取搜索建议
const asyncSearch = async () => {
    if (searchWord.value) {
        const { data } = await axios.get(url + '/word/getTargetWords', {
            params: {
                word: searchWord.value
            }
        });
        suggestions.value = data;
        if (data != []) {
            finished.value = false;
        }
    } else {
        suggestions.value = [];
    }
}

const loadMoreWords = () => {
    loading.value = true;
    axios.get(url + "/word/getMoreWords", { params: { page: page, word: searchWord.value } }).then(resp => {
        if (resp.data == [] || resp.data.length == 0) {
            finished.value = true;
        } else {
            suggestions.value = suggestions.value.concat(resp.data);
        }
    }).finally(() => {
        page += 1;
        loading.value = false;
    })
}

// 选择搜索建议中的单词添加到搜索框并触发搜索
const selectSuggestion = (suggestion) => {
    let parts = suggestion.split("\t", 2);
    searchWord.value = parts[0];
    suggestions.value = [];
    form.wordBookId = routes.params.id; // 绑定
    form.name = parts[0];
    form.definition = parts[1];
};

// 提交表单方法
const submitForm = () => {
    formRef.value.validate().then(() => {
        axios({
            method: 'post',
            url: url + "/word/addWord",
            data: form
        }).then(resp => {
            wordList.value.unshift(resp.data);
            form.remark = "";
            form.name = "";
            form.definition = "";
            alert("添加成功");
        })
    }).catch((error) => {
        // console.log('表单验证失败:', error);
    });
};

// // 监听表单数据变化，更新isFormValid
// watch(() => form, () => {
//     // 可以在这里添加一些逻辑，比如根据表单数据变化动态更新界面显示等
// }, { deep: true });

// 展示已经创建的单词
const showTargetWord = ref(false);
const finishedWords = ref(false);
const loadingWords = ref(false);
const wordList = ref([]);
const targetWord = ref({});
let page2 = 1;
const onLoad = () => {
    loadingWords.value = true;
    axios.get(url + "/word/getWordsByBookId", {
        params: {
            wordBookId: routes.params.id,
            page: page2
        }
    }).then(resp => {
        if (resp.data == [] || resp.data.length == 0) {
            finishedWords.value = true;
        } else {
            wordList.value = wordList.value.concat(resp.data);
        }
    }).finally(() => {
        loadingWords.value = false;
        page2 += 1;
    })
};

const deleteWord = (index, id)=>{

    axios.delete(url + '/word/deleteById?id=' + id).then(resp => {
        wordList.value.splice(index, 1);
    })
}

const onRefresh = () => {
    // 清空列表数据
    finished.value = false;
    loading.value = true;
    onLoad();
};

</script>

<style scoped>
    .vancell:hover{
        color: #1989fa;
    }
</style>